package com.solution.action;

import java.io.IOException;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.solution.constant.LoginConstants;
import com.solution.delegate.ExaminationServiceDelegate;
import com.solution.exception.DelegateException;
import com.solution.exception.ServiceBeanException;
import com.solution.form.LevelForm;
import com.solution.model.LevelType;
import com.solution.model.UserInfo;
import com.solution.util.SearchVO;
import com.solution.webconstant.ExaminationConstant;

public class LevelAction extends Action{

	/**
	 * logging instance.
	 */
	private Logger logger = Logger.getLogger(LevelAction.class.getName());

	/**
	 * Default method.
	 */
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: LevelAction:execute()");
		LevelForm levelForm =(LevelForm)form;
		request.setAttribute("tab", "LEVEL");
		request.setAttribute("editLink", "/searchLevel.do?screen_type=Edit");
		request.setAttribute("viewLink", "/searchLevel.do?screen_type=View");
		request.setAttribute("createLink", "/level.do");

		/**
		 * Creation Case.
		 */
		if("/createLevel".equals(mapping.getPath())){
			request.setAttribute("selectedTab", "create");
			return createLevel(mapping, levelForm, request, response);
		}
		/**
		 * Search Case.
		 */
		else if("/searchLevel".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(levelForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(levelForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return searchLevel(mapping, levelForm, request, response);
		}
		/**
		 * Updation Case.
		 */
		else if("/updateLevel".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(levelForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(levelForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return updateLevel(mapping, levelForm, request, response);
		}
		/**
		 * Edit/View Case.
		 */
		else if("/editViewLevel".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(levelForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(levelForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return editViewLevel(mapping, levelForm, request, response);
		}
		else{
			request.setAttribute("selectedTab", "create");
			return mapping.findForward("init");
		}
	}

	public ActionForward createLevel(ActionMapping mapping,LevelForm levelForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: LevelAction:createLevel()");
		ActionMessages messages = new ActionMessages();
		ActionMessages  errors  = new ActionMessages() ;
		
		LevelType level=null;
		try{
			// obtain the PO.
			level = convertFormToPersistentObject(levelForm,request,"add");
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			level = examinationServiceDelegate.createLevel(level);
			if(level != null){
				messages.add("message", new ActionMessage("Level.add.success"));
				saveMessages(request, messages);
				// set the form parameters for the next navigation.
				if(level.getId() != null){
					levelForm.setLevel_id(level.getId().toString());
				}			
				levelForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_VIEW);
			}
			else{
				errors.add("error", new ActionMessage("Level.add.fail"));
				levelForm.setScreen_type("");
			}
		}
		catch(RemoteException re){
			logger.error(re);
			errors.add("error", new ActionMessage("Level.add.fail"));
			levelForm.setScreen_type("");
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Level.fail.exception", sbe.getMessage()));
			levelForm.setScreen_type("");
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Level.add.fail"));
			levelForm.setScreen_type("");
		}
		catch(ParseException pe){
			logger.error(pe);
			errors.add("error", new ActionMessage("Level.add.fail"));
			levelForm.setScreen_type("");
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: LevelAction:createLevel()");
		return mapping.findForward("createLevel");
	}

	public ActionForward searchLevel(ActionMapping mapping,LevelForm levelForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: LevelAction:searchLevel()");
		ActionMessages errors  = new ActionMessages();
		try{
			HttpSession session = request.getSession();
			UserInfo userInfo = null;
			if(session != null){
				userInfo = (UserInfo)session.getAttribute(LoginConstants.SESSION_USER_INFO);
			}
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			if(levelForm.getShow_list() == null || levelForm.getShow_list().equals("")){
				levelForm.setShow_list("N");
			}
			else{
				// filling the search criteria.
				SearchVO searchVO = new SearchVO();
				List<LevelType> levelList = null;
				if(levelForm.getLevel_name() != null && !"".equals(levelForm.getLevel_name().trim())){
					searchVO.addLikeIgnoreCaseCondition("name", levelForm.getLevel_name().trim());
				}
				if(levelForm.getLevel_description() != null && !"".equals(levelForm.getLevel_description().trim())){
					searchVO.addLikeIgnoreCaseCondition("description", levelForm.getLevel_description().trim());
				}
				if(levelForm.getLevel_status() != null && !levelForm.getLevel_status().equals("")){
					searchVO.addEqualsCondition("status", new Short(levelForm.getLevel_status()));
				}
				searchVO.addEqualsCondition("clientType.id", userInfo.getClientType().getId(), true);
				levelList = examinationServiceDelegate.getLevels(searchVO);
				levelForm.setShow_list("Y");
				if(levelList!=null && levelList.size()>0){
					levelForm.setLevel_list(levelList);
				}
				else{
					errors.add("error", new ActionMessage("Level.search.fail"));
				}
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Level.fail.exception", sbe.getMessage()));
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Level.search.fail"));
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: LevelAction:searchLevel()");
		return mapping.findForward("searchLevel");
	}

	public ActionForward updateLevel(ActionMapping mapping,LevelForm levelForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: LevelAction:updateLevel()");
		ActionMessages messages = new ActionMessages();
		ActionMessages errors  = new ActionMessages() ;
		LevelType level =null;
		try{
			level = convertFormToPersistentObject(levelForm,request,"edit");
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			level = examinationServiceDelegate.modifyLevel(level);
			
			if(level != null){
				messages.add("message", new ActionMessage("Level.update.success"));
				saveMessages(request, messages);
				// set the form parameters for the next navigation.
				if(level.getId() != null){
					levelForm.setLevel_id(level.getId().toString());
				}
				levelForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_VIEW);
			}
			else{
				errors.add("error", new ActionMessage("Level.update.fail"));
				levelForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
			}
		}
		catch(RemoteException re){
			logger.error(re);
			errors.add("error", new ActionMessage("Level.update.fail"));
			levelForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Level.fail.exception", sbe.getMessage()));
			levelForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Level.update.fail"));
			levelForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(ParseException pe){
			logger.error(pe);
			errors.add("error", new ActionMessage("Level.add.fail"));
			levelForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: LevelAction:updateLevel()");
		return mapping.findForward("updateLevel");
	}

	public ActionForward editViewLevel(ActionMapping mapping,LevelForm levelForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: LevelAction:editViewLevel()");
		ActionMessages errors  = new ActionErrors() ;
		try{
			if(levelForm.getLevel_id() != null && !levelForm.getLevel_id().equals("")){
				ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
				LevelType level =examinationServiceDelegate.getLevel(new Long(levelForm.getLevel_id()));
				//fill the form for displaying the details.
				if(level != null){
					levelForm.setLevel_name(level.getName());
					if(level.getDescription() != null){
						levelForm.setLevel_description(level.getDescription());
					}
					if(level.getStatus() != null){
						levelForm.setLevel_status(level.getStatus().toString());
					}
					if(level.getPositiveMark() != null){
						levelForm.setLevel_positive_mark(level.getPositiveMark().toString());
					}
					if(level.getNegativeMark() != null){
						levelForm.setLevel_negative_mark(level.getNegativeMark().toString());
					}
				}
				else{
					errors.add("error", new ActionMessage("Level.details.fail"));
				}
			}
			else{
				errors.add("error", new ActionMessage("Level.details.fail"));
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Level.fail.exception", sbe.getMessage()));
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Level.details.fail"));
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: LevelAction:editViewLevel()");
		return mapping.findForward("editViewLevel");
	}
	
	private LevelType convertFormToPersistentObject(LevelForm levelForm,
			HttpServletRequest request,String pageType) throws ServiceBeanException, DelegateException, IOException, ParseException {
		logger.debug("Entering :: LevelAction:convertFormToPersistentObject()");
		HttpSession session = request.getSession();
		UserInfo userInfo = null;
		if(session != null){
			userInfo = (UserInfo)session.getAttribute(LoginConstants.SESSION_USER_INFO);
		}
		// Creation case.
		LevelType level = new LevelType();
		// modification case.
		ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
		if("edit".equalsIgnoreCase(pageType)){
			logger.info("Update case for the level :"+levelForm.getLevel_id());
			level = examinationServiceDelegate.getLevel(new Long(levelForm.getLevel_id().trim()));
		}
	    // filling the persistent object.
		if(levelForm.getLevel_name()!=null && !"".equals(levelForm.getLevel_name().trim())){
			level.setName(levelForm.getLevel_name().trim());
		}
		if(levelForm.getLevel_description() != null && !"".equals(levelForm.getLevel_description().trim())){
			level.setDescription(levelForm.getLevel_description().trim());
		}
		if(levelForm.getLevel_status() != null && !"".equals(levelForm.getLevel_status().trim())){
			level.setStatus(new Short(levelForm.getLevel_status().trim()));
		}
		if(levelForm.getLevel_positive_mark() != null && !"".equals(levelForm.getLevel_positive_mark().trim())){
			level.setPositiveMark(new Double(levelForm.getLevel_positive_mark().trim()));
		}
		if(levelForm.getLevel_negative_mark() != null && !"".equals(levelForm.getLevel_negative_mark().trim())){
			level.setNegativeMark(new Double(levelForm.getLevel_negative_mark().trim()));
		}
	    // creation case.
		if("add".equalsIgnoreCase(pageType)){
			if(userInfo != null){
				level.setCreatedBy(userInfo.getUsername());
			}
			level.setCreatedOn(new Date());
			level.setClientType(userInfo.getClientType());
		}
		// modification case.
		else{
			if(userInfo != null){
				level.setModifiedBy(userInfo.getUsername());
			}
			level.setModifiedOn(new Date());
		}
		logger.debug("Exiting :: LevelAction:convertFormToPersistentObject()");
		return level;
	}
}
